package com.urea.system.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.urea.common.core.domain.entity.Customer;
import com.urea.common.core.domain.entity.SysUser;
import com.urea.common.exception.ServiceException;
import com.urea.common.utils.SecurityUtils;
import com.urea.common.utils.StringUtils;
import com.urea.system.domain.CustomerAccount;
import com.urea.system.domain.Fleet;
import com.urea.system.domain.vo.FleetUserVo;
import com.urea.system.service.ICustomerAccountService;
import com.urea.system.service.ICustomerService;
import com.urea.system.service.IFleetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.urea.system.mapper.FleetUserMapper;
import com.urea.system.domain.FleetUser;
import com.urea.system.service.IFleetUserService;

/**
 * 车队用户关系Service业务层处理
 * 
 * @author liuzd
 * @date 2023-08-01
 */
@Service
public class FleetUserServiceImpl  extends ServiceImpl<FleetUserMapper, FleetUser> implements IFleetUserService
{
    @Autowired
    private FleetUserMapper fleetUserMapper;
    @Autowired
    private  ICustomerService customerService;
    @Autowired
    private IFleetService fleetService;
    @Autowired
    private ICustomerAccountService customerAccountService;

    /**
     * 查询车队用户关系
     * 
     * @param id 车队用户关系主键
     * @return 车队用户关系
     */
    @Override
    public FleetUser selectFleetUserById(Long id)
    {
        return fleetUserMapper.selectFleetUserById(id);
    }

    /**
     * 查询车队用户关系列表
     * 
     * @param fleetUser 车队用户关系
     * @return 车队用户关系
     */
    @Override
    public List<FleetUserVo> selectFleetUserList(FleetUserVo fleetUser)
    {
        return fleetUserMapper.selectFleetUserList(fleetUser);
    }

    /**
     * 新增车队用户关系
     * 
     * @param fleetUser 车队用户关系
     * @return 结果
     */
    @Override
    public int insertFleetUser(FleetUser fleetUser)
    {
        return fleetUserMapper.insertFleetUser(fleetUser);
    }

    /**
     * 修改车队用户关系
     * 
     * @param fleetUser 车队用户关系
     * @return 结果
     */
    @Override
    public int updateFleetUser(FleetUser fleetUser)
    {
        return fleetUserMapper.updateFleetUser(fleetUser);
    }

    /**
     * 批量删除车队用户关系
     * 
     * @param ids 需要删除的车队用户关系主键
     * @return 结果
     */
    @Override
    public int deleteFleetUserByIds(Long[] ids)
    {
        return fleetUserMapper.deleteFleetUserByIds(ids);
    }

    /**
     * 删除车队用户关系信息
     * 
     * @param id 车队用户关系主键
     * @return 结果
     */
    @Override
    public int deleteFleetUserById(Long id)
    {
        return fleetUserMapper.deleteFleetUserById(id);
    }

    @Override
    public FleetUserVo getFleetInfoByUid(Long uid) {
        return fleetUserMapper.getFleetInfoByUid(uid);
    }

    /**
     * 车队添加用户
     *
     * @param list 用户信息
     */
    @Override
    public void bindFleetUser(List<FleetUserVo> list) {
        Fleet fleet = fleetService.getById(list.get(0).getFleetId());
        for (FleetUserVo vo : list) {
            // 获取手机号 查询
            long uid ;
            Customer customer = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getPhone, vo.getPhone()));
            if (Objects.isNull(customer)) {
//                throw new ServiceException("系统不存在当前用户!");
                Customer cus = new Customer();
                cus.setPhone(vo.getPhone());
                cus.setAccount(vo.getPhone());
                cus.setPassword(vo.getPhone());
                cus.setFleetName(fleet.getFleetName());
                cus.setNickName(vo.getNickName());
                customerService.save(cus);
                uid = cus.getId();
                // 创建账户信息
                CustomerAccount account = new CustomerAccount();
                account.setBalance(BigDecimal.ZERO);
                account.setCreatedTime(LocalDateTime.now());
                account.setCustomerId(cus.getId());
                customerAccountService.save(account);
            }else{
                if (StringUtils.isNotBlank(customer.getFleetName())) {
                    throw new ServiceException(String.format("用户%s:已经绑定车队:%s,请先进行解绑!", customer.getPhone(), customer.getFleetName()));
                }
                Customer update = new Customer();
                update.setId(customer.getId());
                update.setNickName(vo.getNickName());
                update.setFleetName(fleet.getFleetName());
                customerService.updateById(update);
                uid = customer.getId();
            }
            FleetUser fleetUser = new FleetUser();
            fleetUser.setUid(uid);
            fleetUser.setFleetId(vo.getFleetId());
            this.save(fleetUser);
        }
    }

    /**
     * 用户管理-车队用户列表
     *
     * @param vo 条件
     * @return 结果
     */
    @Override
    public List<FleetUserVo> queryFleetUserList(FleetUserVo vo) {
        SecurityUtils.getUserIdByUserType(vo);
        return baseMapper.queryFleetUserList(vo);
    }


    @Override
    public void unbind(FleetUserVo vo) {
        // 如果是队长 且下面存在队员则不给删除
        FleetUser fleetUser = this.getById(vo.getId());
        if ("1".equals(fleetUser.getIsMaster())){
            long count = this.count(Wrappers.lambdaQuery(FleetUser.class).eq(FleetUser::getFleetId, fleetUser.getFleetId()));
            if (count>1){
                throw new ServiceException("车队下存在队员,不可删除队长信息");
            }
        }
        // 根据id 删除用户关系
        deleteFleetUserById(vo.getId());
        // 根据uid更新车队信息
        customerService.update(Wrappers.lambdaUpdate(Customer.class).eq(Customer::getId,vo.getUid())
                .set(Customer::getFleetName,null));
    }

    @Override
    public Map<String, String> queryRoleAndFleetId() {
        Map<String,String> result = new HashMap<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 获取
        Customer one = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getPhone, user.getPhonenumber()));
        if (Objects.nonNull(one)){
            FleetUser fleetUser = getOne(Wrappers.lambdaQuery(FleetUser.class).eq(FleetUser::getUid, one.getId()).eq(FleetUser::getIsMaster, 1));
            if (Objects.nonNull(fleetUser)){
                result.put("fleetId",String.valueOf(fleetUser.getFleetId()));
                Fleet fleet = fleetService.getById(fleetUser.getFleetId());
                result.put("fleetName",String.valueOf(fleet.getFleetName()));

            }
        }
        result.put("userType",user.getUserType());
        result.put("phone",user.getPhonenumber());
        return result;
    }
}
